﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using XinYue.Permission.Mode;

namespace XinYue.Permission.BLL
{
   public class AdminUserService:BaseService<AdminUser>
    {
        #region 多表删除 AdminUser  AdminUserRole  ModuleUser
        public bool DelAdminUser(AdminUser entity)
        {
            using (var db = new PermissionEntities())
            {
                using (var tran = db.Database.BeginTransaction())
                {
                    try
                    {
                        #region 事务提交
                        //先删外键组和管理员表
                        BaseService<ModuleUser> baseService = new BaseService<ModuleUser>();
                        //根据管路员外键id查询组和管理员关联表的主键进行删除
                        Expression<Func<ModuleUser, bool>> ModuleUserWherelambda = c => c.AdminUserId==entity.Id;
                        ModuleUser moduleUser = baseService.Query(ModuleUserWherelambda);
                        baseService.Delete(moduleUser);
                        //再删外键角色和管理员表
                        BaseService<AdminUserRole> baseService1 = new BaseService<AdminUserRole>();
                        //根据管路员外键id查询角色和管理员关联表的主键进行删除
                        Expression<Func<AdminUserRole, bool>> AdminUserRoleWherelambda = c => c.AdminUserId == entity.Id;
                        AdminUserRole adminUserRole = baseService1.Query(AdminUserRoleWherelambda);
                        baseService1.Delete(adminUserRole);
                        //最后删除管理员表
                        BaseService<AdminUser> baseService2 = new BaseService<AdminUser>();
                        baseService2.Delete(entity);
                        //保存
                        db.SaveChanges();
                        //提交
                        tran.Commit();
                        #endregion

                        #region MyRegion
                        ////先删外键组和管理员表
                        //BaseService<ModuleUser> baseService = new BaseService<ModuleUser>();
                        //Expression<Func<ModuleUser, bool>> ModuleUserWherelambda = c => c.AdminUserId == entity.Id;
                        //ModuleUser moduleUser = new ModuleUser();
                        //moduleUser.Id = entity.Id;
                        //baseService.Delete(moduleUser);
                        ////再删外键角色和管理员表
                        //BaseService<AdminUserRole> baseService1 = new BaseService<AdminUserRole>();
                        //AdminUserRole adminUserRole = new AdminUserRole();
                        //adminUserRole.Id = entity.Id;
                        //baseService1.Delete(adminUserRole);
                        ////最后删除管理员表
                        //BaseService<AdminUser> baseService2 = new BaseService<AdminUser>();
                        //baseService2.Delete(entity);
                        ////保存
                        //db.SaveChanges();
                        ////提交
                        //tran.Commit(); 
                        #endregion
                    }
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        Console.WriteLine(ex.Message);
                        return false;
                    }
                }
            }
            return true;
        }
        #endregion

        #region 批量删除 AdminUser  AdminUserRole  ModuleUser
        public bool BatchDeleteByID(string AdminID)
        {
            using (var db = new PermissionEntities())
            {
                using (var tran = db.Database.BeginTransaction())
                {
                    try
                    {
                        #region 事务提交
                        //将string字符串转化为int数组
                        int[] channelCIdArr = Array.ConvertAll(AdminID.Split(','), s => int.Parse(s));
                        for (int i = 0; i < channelCIdArr.Length; i++)
                        {
                            //LINQ to Entities 不支持 LINQ 表达式节点类型“ArrayIndex”,也相当于linq to entities不支持数组索引转换SQL
                            //解决不支持数组索引的方案就是讲要比较的对象声明出来  例如：int ID = channelCIdArr[i];
                            int ID = channelCIdArr[i];
                            //先删外键组和管理员表
                            BaseService<ModuleUser> baseService = new BaseService<ModuleUser>();
                            Expression<Func<ModuleUser, bool>> ModuleUserWherelambda = c => c.AdminUserId == ID;
                            ModuleUser moduleUser = baseService.Query(ModuleUserWherelambda);
                            baseService.Delete(moduleUser);
                            //再删外键角色和管理员表
                            BaseService<AdminUserRole> baseService1 = new BaseService<AdminUserRole>();
                            Expression<Func<AdminUserRole, bool>> AdminUserRoleWherelambda = c => c.AdminUserId == ID;
                            AdminUserRole adminUserRole = baseService1.Query(AdminUserRoleWherelambda);
                            baseService1.Delete(adminUserRole);
                            //最后删除管理员表
                            BaseService<AdminUser> baseService2 = new BaseService<AdminUser>();
                            Expression<Func<AdminUser, bool>> AdminUserWherelambda = c => c.Id == ID;
                            AdminUser adminUser = baseService2.Query(AdminUserWherelambda);
                            baseService2.Delete(adminUser);
                        }
                        //保存
                        db.SaveChanges();
                        //提交
                        tran.Commit();
                        #endregion
                    }
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        Console.WriteLine(ex.Message);
                        return false;
                    }
                }
            }
            return true;
        }
        #endregion

        #region 多表修改 AdminUser  AdminUserRole  ModuleUser
        public bool UpdateAdminUser(AdminUser entity, int roleId, int moudleId)
        {
            using (var db = new PermissionEntities())
            {
                using (var tran = db.Database.BeginTransaction())
                {
                    try
                    {
                        #region 事务提交
                        //在修改管理员之前判断名称是否已存在
                        BaseService<AdminUser> baseService = new BaseService<AdminUser>();
                        Expression<Func<AdminUser, bool>> Wherelambda = c => c.Name.Contains(entity.Name);
                        AdminUser admin = baseService.Query(Wherelambda);
                        //不为空则名称重复 跳出方法不能修改
                        if (admin != null) return false;

                        //修改管理员表 修改之前先根据主键查询一个对象
                        Expression<Func<AdminUser, bool>> AdminUserWherelambda = c => c.Id == entity.Id;
                        AdminUser adminUser = baseService.Query(AdminUserWherelambda);
                        adminUser.Name = entity.Name;
                        adminUser.Password = entity.Password;
                        adminUser.Email = entity.Email;
                        adminUser.Remark = entity.Remark;
                        baseService.Update(adminUser);

                        //修改组和管理员关联表
                        BaseService<ModuleUser> baseService1 = new BaseService<ModuleUser>();
                        Expression<Func<ModuleUser, bool>> ModuleUserWherelambda = c => c.AdminUserId == entity.Id;
                        ModuleUser moduleUser = baseService1.Query(ModuleUserWherelambda);
                        moduleUser.ModuleId = moudleId;
                        baseService1.Update(moduleUser);

                        //修改角色和管理员关联表
                        BaseService<AdminUserRole> baseService2 = new BaseService<AdminUserRole>();
                        Expression<Func<AdminUserRole, bool>> AdminUserRoleWherelambda = c => c.AdminUserId == entity.Id;
                        AdminUserRole adminUserRole = baseService2.Query(AdminUserRoleWherelambda);
                        adminUserRole.RoleId = roleId;
                        baseService2.Update(adminUserRole);
                        //保存
                        db.SaveChanges();
                        //提交
                        tran.Commit();
                        #endregion
                    }
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        Console.WriteLine(ex.Message);
                        return false;
                    }
                }
            }
            return true;
        }
        #endregion

        #region 多表添加  AdminUser  AdminUserRole  ModuleUser
        public bool Add(AdminUser entity, int roleId, int moudleId)
        {
            using (var db = new PermissionEntities())
            {
                using (var tran = db.Database.BeginTransaction())
                {
                    try
                    {
                        #region 事务提交
                        //在添加管理员之前判断名称是否已存在
                        BaseService<AdminUser> baseService = new BaseService<AdminUser>();
                        Expression<Func<AdminUser, bool>> Wherelambda = c => c.Name.Contains(entity.Name);
                        AdminUser adminUser= baseService.Query(Wherelambda);
                        //不为空则名称重复 跳出方法不能添加
                        if (adminUser != null) return false;
                        //添加第一张表
                        entity.Enabled = true;
                        entity.IsDelete = false;
                        entity.CreateTime = DateTime.Now;
                        db.AdminUser.Add(entity);
                        //先保存一次 不然在添加关联表时无法获取管理员ID
                        db.SaveChanges();
                        //添加第二张表
                        AdminUserRole adminUserRole = new AdminUserRole();
                        adminUserRole.RoleId = roleId;
                        adminUserRole.AdminUserId = entity.Id;
                        adminUserRole.CreateTime = DateTime.Now;
                        db.AdminUserRole.Add(adminUserRole);
                        //添加第三张表
                        ModuleUser moduleUser = new ModuleUser();
                        moduleUser.ModuleId = moudleId;
                        moduleUser.CreateTime = DateTime.Now;
                        moduleUser.CreateUserId = entity.Id;
                        moduleUser.AdminUserId = entity.Id;
                        db.ModuleUser.Add(moduleUser);

                        db.SaveChanges();
                        //提交
                        tran.Commit();
                        #endregion
                    }
                    catch (Exception)
                    {
                        tran.Rollback();
                        return false;
                    }
                }
            }
            return true;
        }
        #endregion

        #region 角色表[Role] 组表[Module] 角色与组关联表[ModuleRole] 多表查询
        public List<RoleByModule> SelRoleByModulID(string data)
        {
            int cid = Convert.ToInt32(data);
            using (var db = new PermissionEntities())
            {
                //将数据库查询语句改成Linq表达式
                var result = from a in db.Module
                             join b in db.ModuleRole
                             on a.Id equals b.ModuleId
                             join c in db.Role
                             on b.RoleId equals c.Id
                             where a.Id == cid
                             select new RoleByModule()
                             {
                                 ID = c.Id,
                                 Name=c.Name
                             };
                return result.ToList();
            }
        }
        #endregion

        #region 五表查询    AdminUser  Role  AdminUserRole  ModuleUser  Module
        public List<AdminUserQuery> GetAdminUserQueryList(string RoleName, string data,string AdminName)
        {
            //组
            int cid = Convert.ToInt32(data);
            //角色
            int rid;
            if (RoleName == "") { rid = 0; } else { rid = Convert.ToInt32(RoleName); }
            using (var db = new PermissionEntities())
            {
               
                #region 将数据库查询语句改成Linq表达式 默认查询所有
                var result = from a in db.AdminUser
                              join b in db.ModuleUser
                              on a.Id equals b.AdminUserId
                              join c in db.Module
                              on b.ModuleId equals c.Id
                              join d in db.AdminUserRole
                              on a.Id equals d.AdminUserId
                              join e in db.Role
                              on d.RoleId equals e.Id
                              select new AdminUserQuery()
                              {
                                  //id 登录名 邮箱 所属组名称 角色名称 加入时间 状态 
                                  ID = a.Id,
                                  AdminName = a.Name,
                                  Email = a.Email,
                                  ModuleName = c.Name,
                                  RoleName = e.Name,
                                  CreateTime = a.CreateTime,
                                  Status = a.Enabled,
                                  Remark = a.Remark,
                                  Password = a.Password,
                                  ModuleID = c.Id,
                                  RoleID = e.Id
                              };
                #endregion
                //如果都不为空则根据组，角色，管理员进行查询
                if (cid != 0 && rid != 0 && AdminName != null&& AdminName != "")
                {
                    return result.Where(a => a.ModuleID == cid && a.RoleID == rid && a.AdminName.Contains(AdminName)).ToList();
                }
                //根据组，角色进行查询
                else if (cid != 0 && rid != 0)
                {
                    return result.Where(a => a.ModuleID == cid && a.RoleID == rid).ToList();
                }
                //根据管理员进行查询
                else if (cid != 0) {
                    return result.Where(a =>a.ModuleID== cid).ToList();
                }
                //如果都为空则返回所有
                return result.ToList();

                #region MyRegion
                //#region 根据组，角色，管理员名称查询记录
                //if (cid != 0 && rid != 0 && AdminName != null)
                //{
                //    //将数据库查询语句改成Linq表达式
                //    var result = from a in db.AdminUser
                //                 join b in db.ModuleUser
                //                 on a.Id equals b.AdminUserId
                //                 join c in db.Module
                //                 on b.ModuleId equals c.Id
                //                 join d in db.AdminUserRole
                //                 on a.Id equals d.AdminUserId
                //                 join e in db.Role
                //                 on d.RoleId equals e.Id
                //                 where c.Id == cid && e.Id == rid && a.Name.Contains(AdminName)
                //                 //where e.Id == rid
                //                 select new AdminUserQuery()
                //                 {
                //                     //id 登录名 邮箱 所属组名称 角色名称 加入时间 状态 
                //                     ID = a.Id,
                //                     AdminName = a.Name,
                //                     Email = a.Email,
                //                     ModuleName = c.Name,
                //                     RoleName = e.Name,
                //                     CreateTime = a.CreateTime,
                //                     Status = a.Enabled,
                //                     Remark = a.Remark,
                //                     Password = a.Password,
                //                     ModuleID = c.Id,
                //                     RoleID = e.Id
                //                 };
                //    return result.ToList();
                //}
                //#endregion
                //#region 根据选中的下拉框组名以及下拉框角色名查询记录
                //if (cid != 0 && rid != 0)
                //{
                //    //将数据库查询语句改成Linq表达式
                //    var result = from a in db.AdminUser
                //                 join b in db.ModuleUser
                //                 on a.Id equals b.AdminUserId
                //                 join c in db.Module
                //                 on b.ModuleId equals c.Id
                //                 join d in db.AdminUserRole
                //                 on a.Id equals d.AdminUserId
                //                 join e in db.Role
                //                 on d.RoleId equals e.Id
                //                 where c.Id == cid && e.Id == rid
                //                 // where e.Id == rid
                //                 select new AdminUserQuery()
                //                 {
                //                     //id 登录名 邮箱 所属组名称 角色名称 加入时间 状态 
                //                     ID = a.Id,
                //                     AdminName = a.Name,
                //                     Email = a.Email,
                //                     ModuleName = c.Name,
                //                     RoleName = e.Name,
                //                     CreateTime = a.CreateTime,
                //                     Status = a.Enabled,
                //                     Remark = a.Remark,
                //                     Password = a.Password,
                //                     ModuleID = c.Id,
                //                     RoleID = e.Id
                //                 };
                //    return result.ToList();
                //}
                //#endregion
                //#region 根据选中的下拉框组名查询记录
                //if (cid != 0)
                //{
                //    //将数据库查询语句改成Linq表达式
                //    var result = from a in db.AdminUser
                //                 join b in db.ModuleUser
                //                 on a.Id equals b.AdminUserId
                //                 join c in db.Module
                //                 on b.ModuleId equals c.Id
                //                 join d in db.AdminUserRole
                //                 on a.Id equals d.AdminUserId
                //                 join e in db.Role
                //                 on d.RoleId equals e.Id
                //                 where c.Id == cid
                //                 select new AdminUserQuery()
                //                 {
                //                     //id 登录名 邮箱 所属组名称 角色名称 加入时间 状态 
                //                     ID = a.Id,
                //                     AdminName = a.Name,
                //                     Email = a.Email,
                //                     ModuleName = c.Name,
                //                     RoleName = e.Name,
                //                     CreateTime = a.CreateTime,
                //                     Status = a.Enabled,
                //                     Remark = a.Remark,
                //                     Password = a.Password,
                //                     ModuleID = c.Id,
                //                     RoleID = e.Id
                //                 };
                //    return result.ToList();
                //}
                //#endregion 
                #endregion
            }
        } 
        #endregion
    }
}
